<?php

require_once('OAuth.php');

class Netflix{
	public $consumer = NULL;
	public $token = NULL; 
	private $user_id = NULL;
	public $application_name = NULL; //Needed to create auth-token URL
	public $discQueue = NULL;
    
	public function __construct($consumerKey, $consumerSecret, $applicationName, $oauth_token, $oauth_token_secret, $netflix_user_id) {
		$this->consumer = new OAuthConsumer($consumerKey, $consumerSecret);
		$this->application_name = $applicationName;
		$this->setToken(new OAuthToken($oauth_token, $oauth_token_secret));
		$this->setUserId($netflix_user_id);
	}
	
	public static function checkCredentials($credentialsArray){
		if($credentialsArray == null){
			echo "No credentials given.<br />";
			return false;
		}
		
		$consumer_key = null; 
		$consumer_secret = null;
		$application_name = null;
		
		if(array_key_exists('consumer_key', $credentialsArray)){
			$consumer_key = $credentialsArray['consumer_key'];
		}
		if(array_key_exists('consumer_secret', $credentialsArray)){
			$consumer_secret = $credentialsArray['consumer_secret'];
		}
		if(array_key_exists('application_name', $credentialsArray)){
			$application_name = $credentialsArray['application_name'];
		}
		
		if($consumer_key == null){
			echo "You must specify the consumer key.<br />";
			return false;
		}
		else if($consumer_secret == null){
			echo "You must specify the consumer secret. <br />";
			return false;
		}
		else if($application_name == null){
			echo "You must specify the application name. <br />";
			return false;
		}
		
		return true;
	}
	
	public static function checkDatabaseCredentials($credentialsArray){					
		if(array_key_exists('db_host', $credentialsArray)){
			$db_host = $credentialsArray['db_host'];	
		}
		if(array_key_exists('db_user', $credentialsArray)){
			$db_user = $credentialsArray['db_user'];	
		}
		if(array_key_exists('db_pass', $credentialsArray)){
			$db_pass = $credentialsArray['db_pass'];
		}
		if(array_key_exists('db_name', $credentialsArray)){
			$db_name = $credentialsArray['db_name'];	
		}
	
		if(!empty($db_host) && !empty($db_user) && !empty($db_pass) && !empty($db_name)){
			$db = mysql_connect($db_host, $db_user, $db_pass) or die ('Could not connect: ' . mysql_error());
			mysql_select_db($db_name) or die ('Could not select database');	
		}
	}
	
	private function setTokenFromKeyAndSecret($oauth_token, $oauth_token_secret){
		$token = new OAuthToken($oauth_token, $oauth_token_secret);
		$this->setToken($token);
	}
	
	private function setToken($token){
		$this->token = $token;
		$_SESSION['oauth_token'] = $token->key;
		$_SESSION['oauth_token_secret'] = $token->secret;
	}
	
	public function getToken(){
		return $this->token;
	}
	
	private function setUserId($userId){
		$this->user_id = $userId;
	}
	
	public function getUserId(){
		return $this->user_id;
	}
	
	//FUNCTIONS
	public function getRequestToken(){
		$request_token_endpoint = 'http://api.netflix.com/oauth/request_token';
		$req_req = OAuthRequest::from_consumer_and_token($this->consumer, NULL, "GET", $request_token_endpoint, NULL); //Do not use the token or params in this call
		$req_req->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $this->consumer, NULL);
		$request_curl_file_contents = getURLAsString($req_req->to_url());
		$request_returned_params = array();
		parse_str($request_curl_file_contents, $request_returned_params);
		$oauth_token = $request_returned_params['oauth_token'];
		$oauth_token_secret = $request_returned_params['oauth_token_secret'];
		return new OAuthToken($oauth_token, $oauth_token_secret);
	}
	
	//sends user to netflix, whereupon if they confirm access will be returned to the callback_url.
	public function authorizeRequestToken($oauth_token){
		if(empty($oauth_token)){
			echo "<br />authorizeRequestToken cannot complete because the token is empty<br />";
			return;
		}
		if(!isset($this->application_name)){
			echo "<br />authorizeRequestToken cannot complete because the application_name is not set<br />";
			return;
		}
		if(!isset($this->consumer->key)){
			echo "<br />authorizeRequestToken cannot complete because the consumer_key is not set<br />";
			return;
		}
		
		$auth_token_endpoint = 'https://api-user.netflix.com/oauth/login';
		$callback_url = "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME'] . '/';
		$auth_url = $auth_token_endpoint . "?oauth_token=" . $oauth_token . "&oauth_callback=" . urlencode($callback_url) . "&application_name=" . $this->application_name . "&oauth_consumer_key=" . $this->getConsumerKey();
		Header("Location: $auth_url"); 
	}

	public function getAccessToken($oauth_token, $oauth_token_secret){
		if(empty($oauth_token) || empty($oauth_token_secret)){
			echo "<br />getAccessToken cannot complete because the token information is empty<br />";
			return;
		}
		if(!isset($this->application_name)){
			echo "<br />getAccessToken cannot complete because the application_name is not set<br />";
			return;
		}
		if(!isset($this->consumer->key)){
			echo "<br />getAccessToken cannot complete because the consumer_key is not set<br />";
			return;
		}
		
		$this->setTokenFromKeyAndSecret($oauth_token, $oauth_token_secret);
		
		$access_token_endpoint = 'http://api.netflix.com/oauth/access_token';
		$params = $this->getAccessParams(); //TODO: This is empty. The reason this works is because the token is set in this, so createAuthorizedURL can make the right sig.

		$access_url = $this->createAuthorizedURL($access_token_endpoint, "GET", $params);
		$access_curl_file_contents = getURLAsString($access_url);
		parse_str($access_curl_file_contents, $params);
		
		if(!array_key_exists('oauth_token', $params)){
			echo "No oauth_token found when getting access token <br/>";
			return false;
		}
		else if(!array_key_exists('oauth_token_secret', $params)){
			echo "No oauth_token_secret found when getting access token <br/>";
			return false;
		}
		else if(!array_key_exists('user_id', $params)){
			echo "No user_id found when getting access token <br/>";
			return false;
		}
		else{
			$this->setTokenFromKeyAndSecret($params['oauth_token'], $params['oauth_token_secret']);
			$this->setUserId($params['user_id']);
			return true;
		}
	}
	
	
	public function createAuthorizedURL($url, $method="GET",  $params = NULL){
		$req = OAuthRequest::from_consumer_and_token($this->consumer, $this->token, $method, $url, $params);
		$req->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $this->consumer, $this->token);
		return $req->to_url();
	}
	
	private function getConsumerKey(){
		if(!empty($this->consumer)){
			return $this->consumer->key;
		}
		
		return null;
	}
	
	public function getAccessParams(){
/* 		$access_params = array('oauth_consumer_key' => $this->getConsumerKey()); //TODO:The consumer key may not be necessary */
		return $access_params;
	}
	
	function getUserDetails(){
		$userId = $this->getUserId();
		if(!empty($userId)){
			$feed_url = "http://api.netflix.com/users/" . $userId;
			$toRet = "";
			$access_params = $this->getAccessParams();
			$authURL = $this->createAuthorizedURL($feed_url, "GET", $access_params);
			$feed_contents = getURLAsString($authURL);
			return $feed_contents;
		}
		else{
			echo "<br />getUserDetails() cannot continue because the user_id is not set.<br />";
			return NULL;
		}
	}

	function getUserFeeds(){
		$userId = $this->getUserId();
		if(!empty($userId)){
			$feed_url = "http://api.netflix.com/users/" . $userId . "/feeds";			
			$authURL = $this->createAuthorizedURL($feed_url, "GET", $this->getAccessParams());
			$feed_contents = getURLAsString($authURL);
			return $feed_contents;
		}
		else{
			echo "<br />getUserFeeds() cannot continue because the user_id is not set.<br />";
			return NULL;
		}
	}


	
	function getUserQueues($sort = "queue_sequence", $start_index = 0, $max_results = 25, $updated_min = "0"){
		$userId = $this->getUserId();
		if(!empty($userId)){
      		$feed_url = "http://api.netflix.com/users/" . $userId . "/queues";		
      		$access_params = $this->getAccessParams();
      		$access_params['sort'] = $sort;
      		$access_params['start_index'] = $start_index;
      		$access_params['max_results'] = $max_results;
      //		$access_params['updated_min'] = $update_min; //TODO:Cannot be empty
      		
      		$authURL = $this->createAuthorizedURL($feed_url, "GET", $access_params);
      		$feed_contents = getURLAsString($authURL);
      		return $feed_contents;
		}
		else{
			echo "<br />getUserQueues() cannot continue because the user_id is not set.<br />";
			return NULL;
		}
	}

	function getUserQueueDisc($sort = "queue_sequence", $start_index = 0, $max_results = 25, $updated_min = ""){
		if($this->discQueue == NULL){
		    $this->discQueue = new NetflixQueue($this->user_id, QUEUE_TYPE_DISC, $this);
    	}
		return $this->discQueue;
	}
	
	function getUserQueueInstant($sort = "queue_sequence", $start_index = 0, $max_results = 25, $updated_min = ""){
	    $discQueue = new NetflixQueue($this->user_id, QUEUE_TYPE_INSTANT, $this);
		return $discQueue;
	}
  
  function saveUserToDB($username, $netflix_user_id, $oauth_token, $oauth_token_secret){
		//Check if user already exists in DB
		mysql_connect('localhost', 'root', 'at!admin');
		mysql_select_db('netflix_db');
		$query = "select count(*) from user where user.username = '$username'";
		$result= mysql_query($query) or die("Query $query failed: " . mysql_error());
		$exists = mysql_fetch_array($result, MYSQL_NUM);
		if($exists[0] == 0){
		      $query="INSERT INTO user (username, netflix_user_id, oauth_token, oauth_token_secret) 
		      			VALUES ('$username', '$netflix_user_id', '$oauth_token', '$oauth_token_secret')";
		      $result= mysql_query($query) or die("Query $query failed: " . mysql_error());
		      echo "Added $username to the database";
		}
		else{
		      echo "<br />User $username already exists in database";
		}
	}
	
	//Non-user protected services
  function searchByTitle($title, $start_index = 0, $max_results = 25){ //Only needs a consumer key
		$url = "http://api.netflix.com/catalog/titles";
		if($title){
			$title = urlencode($title);
			$params['term'] = $title;
			$params['start_index'] = $start_index;
			$params['max_results'] = $max_results;
			$searchResults = getURLAsString($this->createAuthorizedURL($url, "GET", $params));
			return $searchResults;
		}
		
		return null;
	}
}

	function postURLAsString($url, $data){
		if($url){
	    	$ch = curl_init($url);
			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_POST, 1); 
			$output= curl_exec($ch);
			curl_close($ch);
	/*       echo "POST of url <a href=\"$url\">$url</a> returned html '" . htmlspecialchars($output) . "'<br />"; */
			return $output;
		}
		
		return null;    
	}
      
	function getURLAsString($url, $method="GET"){
		if($url){
			$ch = curl_init($url);
			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);     
			$output = curl_exec($ch);      
			curl_close($ch);
	/*       echo "GET of url <a href=\"$url\">$url</a> returned html '" . htmlspecialchars($output) . "'<br />"; */
			return $output;
		}
		
		return null;
	}


?>
